//
//  HMPhoneNumSignInViewController.m
//  获得
//
//  Created by mac on 17/1/7.
//  Copyright © 2017年 mac.gu. All rights reserved.
//
#import "HMNetWorkTool.h"
#import "HMPhoneNumSignInViewController.h"
#import "HMAppAgreementViewController.h"
#import "HMWhatInvitationViewController.h"
#import "HMPhoneNumLoginViewController.h"
#import "UIViewController+Extension.h"
#import <SMS_SDK/SMSSDK.h>
#import "HMPhoneNum.h"
#import "HMRegistPhoneViewModel.h"
#import "HMRegistModel.h"
#import "TPKeyboardAvoidingScrollView.h"
#import "SGSaveFile.h"
@interface HMPhoneNumSignInViewController ()
{
    NSInteger  buttonIndex;
}

//用户名
@property (nonatomic, strong) UITextField *txtUserName;

//验证码
@property (nonatomic, strong) UITextField *txtCode;

//获取验证码
@property (nonatomic, strong) UIButton *btnGetCode;
//密码
@property (nonatomic, strong) UITextField *txtPassWord;

//邀请码
@property (nonatomic, strong) UITextField *txtInvitation;

//用户协议
@property (nonatomic, strong) UIButton *btnAgreement;
//神马是邀请码
@property (nonatomic, strong) UIButton *btnWhatInvitation;
//注册按钮
@property (nonatomic, strong) UIButton *btnRegister;
//定时器
@property (nonatomic,retain) NSTimer * timer;

@property (nonatomic, strong) NSArray *registArr;

@end

@implementation HMPhoneNumSignInViewController
#define WeakSelf(VC) __weak VC *weakSelf = self

- (void)dealloc{
    if ([self.timer isValid]) {
        [self.timer invalidate];
        self.timer = nil;
    }
}
- (void)stopTimer{
    [self.timer invalidate];
    
    self.timer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    buttonIndex = 60;
    self.automaticallyAdjustsScrollViewInsets = NO;
//    简单点说就是automaticallyAdjustsScrollViewInsets根据按所在界面的status bar，navigationbar，与tabbar的高度，自动调整scrollview的 inset,设置为no，不让viewController调整，我们自己修改布局即可~
    
    self.view = [[TPKeyboardAvoidingScrollView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    
    self.view.backgroundColor = [UIColor colorWithHex:0xffffff];
 
    [self setupUI];
    
}


- (void)setupUI{
    
    self.title = @"注册";
    //添加用户名
    [self.view addSubview:self.txtUserName];
    [_txtUserName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.width.offset(260);
        make.top.offset(64 + 64);
        make.height.offset(40);
    }];
    [self.view addSubview:self.txtCode];
    [_txtCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_txtUserName);
        make.top.equalTo(_txtUserName.mas_bottom).offset(15);
        make.height.equalTo(_txtUserName);
        make.width.offset(150);
    }];
    
    //获取验证码按钮
    [self.view addSubview:self.btnGetCode];
    [_btnGetCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_txtUserName);
        make.height.top.equalTo(_txtCode);
        make.width.offset(60);
        
    }];
    
    //输入密码
    [self.view addSubview:self.txtPassWord];
    [_txtPassWord mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(_txtUserName);
        make.top.equalTo(_btnGetCode.mas_bottom).offset(15);
        
    }];

    //输入邀请码
    [self.view addSubview:self.txtInvitation];
    [_txtInvitation mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(_txtUserName);
        make.top.equalTo(_txtPassWord.mas_bottom).offset(15);
        
    }];
    //用户协议
    [self.view addSubview:self.btnAgreement];
    [_btnAgreement mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_txtUserName);
        make.top.equalTo(_txtInvitation.mas_bottom).offset(15);
        
    }];
    //什么是邀请码
    [self.view addSubview:self.btnWhatInvitation];
    [_btnWhatInvitation mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_txtUserName);
        make.top.equalTo(_txtInvitation.mas_bottom).offset(15);
        
    }];
    //注册
    [self.view addSubview:self.btnRegister];
    [_btnRegister mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_txtUserName);
        make.top.equalTo(_btnWhatInvitation.mas_bottom).offset(15);
        make.height.offset(40);
    }];
    
    
    
    
    

}

- (void)btnLoginAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (UITextField *)txtUserName{
    if (!_txtUserName) {
        _txtUserName = [[UITextField alloc] init];
        
        //是否纠错
        _txtUserName.autocorrectionType = UITextAutocorrectionTypeNo;
        _txtUserName.keyboardType = UIKeyboardTypeNumberPad;
        _txtUserName.font = [UIFont systemFontOfSize:15];
        _txtUserName.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入手机号" attributes:@{NSForegroundColorAttributeName: [UIColor colorWithHex:0x999999]}];
        _txtUserName.textColor = [UIColor orangeColor];
        _txtUserName.layer.borderColor = [UIColor colorWithHex:0xcccccc].CGColor;
        
        _txtUserName.layer.borderWidth = 0.5;
        _txtUserName.layer.masksToBounds = YES;
        _txtUserName.layer.cornerRadius = 4;
        _txtUserName.backgroundColor = [UIColor colorWithHex:0xffffff];
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 10, 40)];
        _txtUserName.leftView = img;
        
        _txtUserName.leftViewMode = UITextFieldViewModeAlways;
    }
    return _txtUserName;
}

- (UITextField *)txtCode{
    if (!_txtCode) {
        _txtCode = [[UITextField alloc] init];
        
        //是否纠错
        _txtCode.autocorrectionType = UITextAutocorrectionTypeNo;
        _txtCode.keyboardType = UIKeyboardTypeNumberPad;
        _txtCode.font = [UIFont systemFontOfSize:15];
        _txtCode.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:@{NSForegroundColorAttributeName: [UIColor colorWithHex:0x999999]}];
        _txtCode.textColor = [UIColor orangeColor];
        _txtCode.layer.borderColor = [UIColor colorWithHex:0xcccccc].CGColor;
        _txtCode.layer.borderWidth = 0.5;
        _txtCode.layer.masksToBounds = YES;
        _txtCode.layer.cornerRadius = 4;
        _txtCode.backgroundColor = [UIColor colorWithHex:0xffffff];
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 10, 40)];
        _txtCode.leftView = img;
        
        _txtCode.leftViewMode = UITextFieldViewModeAlways;
    }
    return _txtCode;
}

- (UIButton *)btnGetCode{
    if (!_btnGetCode) {
        _btnGetCode = [UIButton buttonWithType:UIButtonTypeCustom];
        
        _btnGetCode.backgroundColor = [UIColor orangeColor];
        _btnGetCode.titleLabel.font = [UIFont systemFontOfSize:13];
        [_btnGetCode setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_btnGetCode setTitle:@"获取" forState:UIControlStateNormal];
        _btnGetCode.layer.masksToBounds = YES;
        _btnGetCode.layer.cornerRadius = 25/2;
        [_btnGetCode addTarget:self action:@selector(btnGetCodeAction) forControlEvents:UIControlEventTouchUpInside];
        
        
    }
    return _btnGetCode;
}
- (void)creatTimer
{
    _timer =[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(appAction) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}
- (void)appAction
{
    [self.btnGetCode setTitle:[NSString stringWithFormat:@"%ld秒",(long)buttonIndex--] forState:UIControlStateNormal];
    if (buttonIndex <= 0) {
        [_timer setFireDate:[NSDate distantFuture]];
        [self.btnGetCode setTitle:[NSString stringWithFormat:@"重新获取"] forState:UIControlStateNormal];
        buttonIndex = 10;
    }
}



- (void)btnGetCodeAction{
    if ([HMPhoneNum isMobile:_txtUserName.text] != YES) {
        [self showHudAuto:@"请输入正确手机号" andDuration:@"1"];
    }else{
        if (buttonIndex == 60 || self.timer == nil) {
            [self creatTimer];
            
            [self showHudAuto:@"正在发送" andDuration:@"1"];
            WeakSelf(HMPhoneNumSignInViewController);
            

            [[HMNetWorkTool sharedTool]requstCodeNum:weakSelf.txtUserName.text Finished:^(id responseObject) {
                
                [weakSelf showHudAuto:@"发送成功" andDuration:@"1"];
                [weakSelf stopTimer];
            } Failed:^(NSError *error) {
                NSLog(@"%@",error); 
                [weakSelf showHudAuto:@"发送失败" andDuration:@"1"];
            }];

        }
    }
}



- (UITextField *)txtPassWord{
    if (!_txtPassWord) {
        _txtPassWord = [[UITextField alloc] init];
        
        //是否纠错
        _txtPassWord.autocorrectionType = UITextAutocorrectionTypeNo;
        _txtPassWord.font = [UIFont systemFontOfSize:15];
        _txtPassWord.secureTextEntry = YES;
        _txtPassWord.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:@{NSForegroundColorAttributeName: [UIColor colorWithHex:0x999999]}];
        _txtPassWord.textColor = [UIColor orangeColor];
        _txtPassWord.layer.borderColor = [UIColor colorWithHex:0xcccccc].CGColor;
        _txtPassWord.layer.borderWidth = 0.5;
        _txtPassWord.layer.masksToBounds = YES;
        _txtPassWord.layer.cornerRadius = 4;
        _txtPassWord.backgroundColor = [UIColor colorWithHex:0xffffff];
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 10, 40)];
        _txtPassWord.leftView = img;
        
        _txtPassWord.leftViewMode = UITextFieldViewModeAlways;
    }
    return _txtPassWord;
}



- (UITextField *)txtInvitation{
    if (!_txtInvitation) {
        _txtInvitation = [[UITextField alloc] init];
        
        //是否纠错
        _txtInvitation.autocorrectionType = UITextAutocorrectionTypeNo;
        _txtInvitation.font = [UIFont systemFontOfSize:15];
        _txtInvitation.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入邀请码" attributes:@{NSForegroundColorAttributeName: [UIColor colorWithHex:0x999999]}];
        _txtInvitation.textColor = [UIColor orangeColor];
        _txtInvitation.layer.borderColor = [UIColor colorWithHex:0xcccccc].CGColor;
        _txtInvitation.layer.borderWidth = 0.5;
        _txtInvitation.layer.masksToBounds = YES;
        _txtInvitation.layer.cornerRadius = 4;
        _txtInvitation.backgroundColor = [UIColor colorWithHex:0xffffff];
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 10, 40)];
        _txtInvitation.leftView = img;
        
        _txtInvitation.leftViewMode = UITextFieldViewModeAlways;
    }
    return _txtInvitation;
}


- (UIButton *)btnAgreement{
    if (!_btnAgreement) {
        _btnAgreement = [UIButton buttonWithType:UIButtonTypeCustom];
 
        [_btnAgreement setTitleColor:[UIColor colorWithHex:0x888888] forState:UIControlStateNormal];
        _btnAgreement.titleLabel.font = [UIFont systemFontOfSize:12];
        [_btnAgreement setTitle:@"《获得APP用户协议》" forState:UIControlStateNormal];
        [_btnAgreement sizeToFit];
        [_btnAgreement addTarget:self action:@selector(btnAgreementAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _btnAgreement;
}



- (UIButton *)btnWhatInvitation{
    if (!_btnWhatInvitation) {
        _btnWhatInvitation = [UIButton buttonWithType:UIButtonTypeCustom];
       
        [_btnWhatInvitation setTitleColor:[UIColor colorWithHex:0x999999] forState:UIControlStateNormal];
        _btnWhatInvitation.titleLabel.font = [UIFont systemFontOfSize:12];
        [_btnWhatInvitation setTitle:@"什么是邀请码" forState:UIControlStateNormal];
        [_btnWhatInvitation sizeToFit];
        
        [_btnWhatInvitation addTarget:self action:@selector(btnWhatInvitationAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _btnWhatInvitation;
}

- (void)btnWhatInvitationAction{
//    WhatInvitationViewController *whatInvitationVc = [[WhatInvitationViewController alloc] init];
//    [self.navigationController pushViewController:whatInvitationVc animated:YES];
}

- (UIButton *)btnRegister{
    if (!_btnRegister) {
        _btnRegister = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [_btnRegister setTitleColor:[UIColor colorWithHex:0xffffff] forState:UIControlStateNormal];
        _btnRegister.titleLabel.font = [UIFont systemFontOfSize:17];
        [_btnRegister setTitle:@"立即注册" forState:UIControlStateNormal];
        _btnRegister.layer.masksToBounds = YES;
        _btnRegister.layer.cornerRadius = 5;
        _btnRegister.backgroundColor = [UIColor orangeColor];
        
        [_btnRegister addTarget:self action:@selector(btnRegistAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _btnRegister;
}
//用户协议点击事件
- (void)btnAgreementAction{
    HMAppAgreementViewController *appAgreementVc = [[HMAppAgreementViewController  alloc] init];
    appAgreementVc.view.backgroundColor = [UIColor colorWithHex:0xffffff];
    [self.navigationController pushViewController:appAgreementVc animated:YES];
}

- (void)btnRegistAction{

    if ([HMPhoneNum isMobile:self.txtUserName.text] != YES) {
        [self showHudAuto:@"请输入正确手机号" andDuration:@"1"];
    }else if ([self.txtCode.text isEqualToString:@""]) {
        [self showHudAuto:@"请输入验证码" andDuration:@"1"];
    }else if ([HMPhoneNum validatePassword:self.txtPassWord.text] != YES) {
        [self showHudAuto:@"密码长度不少于6位" andDuration:@"1"];
    }else{
    
        [self commitCode];
    }
    
   
}


//- (void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    self.navigationController.navigationBarHidden = YES;
//}
//
//- (void)viewWillDisappear:(BOOL)animated{
//    [super viewWillDisappear:animated];
//    self.navigationController.navigationBarHidden = NO;
//}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)commitCode{
    [self showHudWaitingView:@"请稍等"];
    
    [HMRegistPhoneViewModel postRegistPhoneNum:_txtUserName.text andPassword:_txtPassWord.text Finished:^(id responseObject) {

        WeakSelf(HMPhoneNumSignInViewController);
        NSString *code = responseObject[@"code"];
        NSInteger intCode = code.integerValue;
        if (intCode == 200) {
            [weakSelf removeMBProgressHudInManaual];
//            [weakSelf showHudAuto:@"注册成功" andDuration:@"1"];
            HMPhoneNumLoginViewController *loginVC =[[HMPhoneNumLoginViewController alloc]init];
            //  设置标记
            loginVC.isGuide = weakSelf.isGuide;
            [weakSelf.navigationController pushViewController:loginVC animated:YES];
//            NSLog(@"%@",responseObject);
//            responseObject[@"data"][@"token"];
//            [SGSaveFile saveObjectToSystem:responseObject[@"data"][@"token"] forKey:@"userToken"];
            
            
            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"data"][@"token"] forKey:@"idToken"] ;
            
            //                [weakSelf.navigationController popViewControllerAnimated:YES];
        }else if (intCode == -1){
            [weakSelf showHudAuto:@"账号已注册" andDuration:@"1"];
        }else{
            [weakSelf showHudAuto:@"未知错误" andDuration:@"1"];
        }
        
    } Failed:^(NSError *error) {
//        [weakSelf showHudAuto:@"注册失败" andDuration:@"1"];
    }];
    
    //提交验证码
//    [[HMNetWorkTool sharedTool]requstCommitCode:_txtCode.text andPhoneNum:_txtUserName.text Finished:^(id responseObject) {
//        WeakSelf(HMPhoneNumSignInViewController);
//        
//        
//    } Failed:^(NSError *error) {
//         NSLog(@"错误信息:%@",error);
//        
//        [self removeMBProgressHudInManaual];
//    }];
    
}


@end
